#include "BlockQueue.hpp"
#include <pthread.h>
#include <unistd.h>

using namespace BlockQueueModule;

void *Consumer(void *args)
{
    BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);

    while (true)
    {
        sleep(2);
        int data;
        bq->Pop(&data);

        printf("Consumer,get a data:%d\n", data);
    }
}

void *Productor(void *args)
{
    BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    static int data = 10;
    static pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; // 用于保护 data
    while (true)
    {
        pthread_mutex_lock(&data_mutex); // 加锁
        int local_data = data++;         // 保护对 data 的访问
        pthread_mutex_unlock(&data_mutex); // 解锁
        
        bq->Equeue(data);

        printf("Productor:生产了一个数据:%d\n", data);
    }
}

int main()
{
    BlockQueue<int> *bq = new BlockQueue<int>();

    pthread_t c, p, c1, p2, p1;
    pthread_create(&c, nullptr, Consumer, bq);
    pthread_create(&p2, nullptr, Productor, bq);
    pthread_create(&c1, nullptr, Consumer, bq);
    pthread_create(&p, nullptr, Productor, bq);
    pthread_create(&p1, nullptr, Productor, bq);

    pthread_join(c, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(c1, nullptr);
    pthread_join(p, nullptr);
    pthread_join(p1, nullptr);
    return 0;
}